package stack;

import java.util.Stack;

public class DecodeString {
    public static String decodeString(String s) {
        Stack<Integer> numStack = new Stack<>();
        Stack<String> strStack = new Stack<>();

        int currentNum = 0;
        StringBuilder currentStr = new StringBuilder();

        for (char ch : s.toCharArray()) {
            if (Character.isDigit(ch)) {
                currentNum = currentNum * 10 + Character.getNumericValue(ch);
            } else if (ch == '[') {
                numStack.push(currentNum);
                strStack.push(currentStr.toString());
                currentNum = 0;
                currentStr = new StringBuilder();
            } else if (ch == ']') {
                int num = numStack.pop();
                StringBuilder temp = new StringBuilder();
                for (int i = 0; i < num; i++) {
                    temp.append(currentStr);
                }
                currentStr = new StringBuilder(strStack.pop() + temp.toString());
            } else {
                currentStr.append(ch);
            }
        }

        return currentStr.toString();
    }

    public static void main(String[] args) {
        System.out.println(decodeString("3[a]2[bc]"));  // 输出："aaabcbc"
        System.out.println(decodeString("3[a2[c]]"));   // 输出："accaccacc"
        System.out.println(decodeString("2[abc]3[cd]ef"));  // 输出："abcabccdcdcdef"
        System.out.println(decodeString("abc3[cd]xyz"));   // 输出："abccdcdcdxyz"
    }
}
